//$(function(){
//	$.getJSON('test.json', function(json, textStatus) {
//		console.log(json)
//		startinit(json)
//	});
//	console.log(0)
//})

function startinit(jsondata){
	console.log(jsondata.data);
	var tit_all = jsondata.title,//详情页titile
		img_banner = jsondata.bannerImg,//banner图
		payType = jsondata.payType,//预约or购买
		isSeason = jsondata.isSeason,//是否有通票
		seasonImg = jsondata.seasonImg,//通票底图
		seasonPrize = jsondata.seasonPrize,//通票价钱
		dateHtml = decodeURIComponent(jsondata.dateHtml),//时间地点html
		detailHtml = decodeURIComponent(jsondata.detailHtml),//详情html
		lists = jsondata.data;//单日票
	$(function(){
		init();
	})

	var _userId = getValue('userId')
	var _ifshare = getValue('if_share');//是不是从app里分享出来的页面
	var _mobile = '';//是不是从app里打开的
	var _isnew = getValue('m_source');//是不是新版本
	var http_head = "http://user.zhengzai.tv";//http://user.zhengzai.tv  http://182.92.167.30
	var http_api = "http://api.zhengzai.tv";//http://api.zhengzai.tv  http://182.92.167.30:9081
	var http_download = "http://a.app.qq.com/o/simple.jsp?pkgname=com.modernsky.istv";//下载app页面

	if(_isnew){
		_mobile = getValue('m_source')
	}else{
		//考虑新老版本更替问题 即用户不更新新版本 也要能正常操作
		_mobile = (/MicroMessenger/.test(navigator.userAgent))?'wx':(/iPhone/i.test(navigator.userAgent)||/iPad/i.test(navigator.userAgent))?'ios':(/android/i.test(navigator.userAgent))?'android':'other'
	}

	var k = new Array();
	var _body = new Array();
	var _type = "";



	// 初始化
	function init(){
		addstr();
		setBtnPlay();
		
		// h5加header
		if(_mobile=="wx"||_mobile=="other"||_ifshare){
			$('body').children().wrapAll('<div id="body"></div>');
			loadTopbar(tit_all);
		}
	}

	// 初始化a链接
	function initHref(){
		// IOS和h5的链接
		var _wrap = $('.ticket-list');
		var _lis = $('li:not(.li-last)',_wrap);
		var url = http_api+"/info/video/videoDetail?videoId="
		_lis.each(function(e){
			var _this = $(this);
			var _code = lists[e].videoId;
			var vtype = lists[e].iosType;
			_url = url+_code;
			$.ajax({
				type: "get",
				dataType: "jsonp",
				url: _url,
				success: function(data){
					var _begintime = new Date(data.data.showTime.time);
					var _endtime = new Date(data.data.endTime.time);
					var _nowtime = new Date();
					var albumId = data.data.albumId;
					if(_begintime<_nowtime && _nowtime<_endtime){
						if(_mobile=="ios"&&!_ifshare){
							// 从iosAPP打开
							_this.find('.btn-play').attr('href','zhengzai://videoId='+_code+'&albumId='+albumId+'&type='+vtype);
						}else if(_mobile=="android"&&!_ifshare){
							// 从androidAPP打开
						}else if(_mobile=="wx"||_mobile=="other"){
							// 从浏览器打开（包括分享或h5）
							if(vtype=='3'){
								_this.find('.btn-play').attr('href','../pages/live.html?videoId='+_code);
							}else{
								_this.find('.btn-play').attr('href','../pages/video.html?videoId='+_code);
							}
						}
					}
				},
				error: function(){
					tipShow("error")
				}
			})
		})
	}

	// 添加结构
	function addstr(){
		var _num = lists.length;
		var _wrap = $('.ticket-list');
		var _str = '';
		for(var i=0;i<_num;i++){
			var _li = lists[i];
			_str +=  '<li class="li-buy" video-code="'+_li.videoId+'" ios-type="'+_li.iosType+'" prize="'+_li.prize+'" set-name="'+_li.title+'">'
			_str +=	'<div class="bg"><img src="'+_li.img+'"></div><div class="btn"></div></li>'
		}
		if(isSeason==1){
			_str += '<li class="li-last li-buy" prize="'+seasonPrize+'">'
			_str +=	'<div class="bg"><img src="'+seasonImg+'"></div>'
			_str +=	'<div class="btn"></div></li>'
		}
		$('.banner').html('<img src="'+img_banner+'" alt="">');
		$('.info').html(dateHtml);
		_wrap.html(_str);
		$('.list').html(detailHtml);
	}

	// 初始化播放按钮
	function setBtnPlay(){
		var _wrap = $('.ticket-list');
		var _lis = $('.li-buy:not(.li-last)',_wrap);
		//var _bought = data.data; //已购买的视频代码
		_type = payType;
		_lis.each(function(e){
			var _str = ''
			var _this = $(this);
			var _code = lists[e].videoId; //本地设置的视频代码
			//if($.inArray(_code,_bought)>=0){
			//	_str+='<a class="btn-play" href="javascript:void(0)"></a>'
			//	_this.removeClass('li-buy').addClass('li-play');
			//	$('.li-last').remove();
			//}else{
				if(_type == 1){
					_str+='<div class="button btn-buy" style="margin-left:-5.5px;"><span class="buy" style="line-height:18px; padding-top:4px;">购买<br/>(¥'+lists[e].prize+')</span></div>'
				}else{
					_str+='<div class="button btn-buy"><span class="buy" style="line-height:42px;">预约</span></div>'
				}
			//}
			_this.find('.btn').html(_str);
		})
		//var _url = http_head+"/m/pay/list_id?userId="+_userId;
		//$.ajax({
		//	type: "get",
		//	dataType: "jsonp",
		//	url: _url,
		//	success:function(data){
		//
		//		if(_type == 1){
		//			$('.li-last').find('.btn').html('<div class="button btn-buy black" style="margin-left:-5.5px;"><span class="buy" style="line-height:18px; padding-top:4px;">购买<br/>(¥'+seasonPrize+')</span></div>')
		//			$('.left-stuff').html('<div class="total-prize">合计：<span>¥ <b></b></span></div>')
		//			$('#btn-pay').css("lineHeight","42px").find('.buy').html("支付")
		//		}else{
		//			$('.li-last').find('.btn').html('<div class="button btn-buy black"><span class="buy" style="line-height:42px;">提交</span></div>')
		//			$('#btn-pay').find('.buy').html("提交")
		//		}
		//		initHref();
		//		playClick();
		//		chooseTickets();
		//		finalPay();
		//	},
		//	error:function(){
		//		tipShow("error")
		//	}
		//})
	}

	// 选票
	function chooseTickets(){
		var _wrap = $('.ticket-list');
		var _disk = $('.pay-disk');
		var _lis = $('.li-buy:not(.li-last)',_wrap);
		var _last = $('.li-last',_wrap);
		var _intro = $('.list');

		_lis.each(function(){
			var _this = $(this);
			_this.find('.btn-buy').click(function(){
				_this.toggleClass('li-buy').toggleClass('li-active');
				_this.find('.btn-buy').toggleClass('blue');
				var _active = $('.li-active:not(.li-last)');
				if(_active.length == _lis.length){
					_last.removeClass('li-buy').addClass('li-active');
					_last.find('.btn-buy').addClass('blue');
					$('.total-prize').find('b').html(seasonPrize);
				}else{
					_last.addClass('li-buy').removeClass('li-active');
					_last.find('.btn-buy').removeClass('blue');
				}
				if(_lis.hasClass('li-active')){
					var _prize = 0;
					for(var i=0;i<_active.length;i++){
						_prize+=parseInt(_active.eq(i).attr('prize'))
					}
					if(_last.hasClass('li-active')){
						_prize = parseInt(_last.attr('prize')).toFixed(2);
					}else{
						_prize = _prize.toFixed(2);
					}
					$('.total-prize').find('b').html(_prize);
					_intro.addClass('on');
					_disk.show();
					_type==0&&getCoupon();
				}else{
					_intro.removeClass('on');
					_disk.hide();
				}
			})
		})
		_last.find('.btn-buy').click(function(){
			var _this = _last;
			$('.total-prize').find('b').html(parseInt(_this.attr('prize')).toFixed(2));
			if(_this.hasClass('li-buy')){
				$('li:not(.li-play)',_wrap).removeClass('li-buy').addClass('li-active');
				$('li:not(.li-play)',_wrap).find('.btn-buy').addClass('blue');
				_intro.addClass('on');
				_disk.show();
				_type==0&&getCoupon();
			}else if(_this.hasClass('li-active')){
				$('li:not(.li-play)',_wrap).removeClass('li-active').addClass('li-buy');
				$('li:not(.li-play)',_wrap).find('.btn-buy').removeClass('blue');
				_intro.removeClass('on');
				_disk.hide();
			}
		})
	}

	// 提交
	function finalPay(){
		var _btn = $('#btn-pay');
		
		var v_data = new Array();
		var p_data = new Array();
		var n_data = new Array();
		var allin = 0;

		window.onerror = function(err) {}
		function connectWebViewJavascriptBridge(callback) {
			if (window.WebViewJavascriptBridge){
				callback(WebViewJavascriptBridge)
			} else {
				document.addEventListener('WebViewJavascriptBridgeReady', function() {
					callback(WebViewJavascriptBridge)
				}, false)
			}
		}
		function order(){
			_btn.click(function(e){
				if(!_userId){
					window.location.href="../pages/login.html";
				}else{
					var _lis = $('.li-active:not(.li-last)',$('.ticket-list'));
					_lis.each(function(){
						var _this = $(this);
						k.push(_this.attr('video-code'));
						_body.push(_this.attr('set-name'));
					})
					var _url = http_head+"/api/wxpay/prepay_id?body="+_body+"&userId="+_userId+"&videoId="+k+"&totalFee=0&clientIp=192.168.200.174&tradeType=APP&voucherCode="+"&bodySuf="+payType
					$.ajax({
						type: "post",
						dataType: "jsonp",
						url: _url,
						success: function(){ //点击支付按钮以后
							tipShow('预约成功');
							$('.pay-disk').hide();
							setInterval(function(){
								location.reload();
							},2000)
						},
						error: function(){
							tipShow('预约失败')
						}
					})
					k = []
				}
			})
		}

		// 如果是预约
		if(_type==0){
			if(_mobile=="ios"&&!_ifshare){
				if(_isnew){
					connectWebViewJavascriptBridge(function(bridge){
						bridge.init(function(message, responseCallback) {
							var data = {'init': 'success'}
							responseCallback(data)
						})

						bridge.registerHandler('loginJSHandler', function(data, responseCallback) {
							_userId = data.userId;
							setBtnPlay();
							return _userId;
						})

						bridge.registerHandler('switchToFront', function(data, responseCallback) {
							if(data){
								setBtnPlay();
							}
						})
						order();
					})
				}else{
					order();
				}
			}else{
				order();
			}
		// 如果是购买
		}else if(_type==1){
			if(_mobile=="ios"&&!_ifshare){
				if(_isnew){
					connectWebViewJavascriptBridge(function(bridge){
						bridge.init(function(message, responseCallback) {
							var data = {'init': 'success'}
							responseCallback(data)
						})

						bridge.registerHandler('loginJSHandler', function(data, responseCallback) {
							_userId = data.userId;
							setBtnPlay();
							return _userId;
						})

						bridge.registerHandler('switchToFront', function(data, responseCallback) {
							if(data){
								setBtnPlay();
							}
						})

						var callbackButton = document.getElementById('btn-pay')
						callbackButton.onclick = function(e){
							e.preventDefault()
							var _lis = $('.li-active:not(.li-last)',$('.ticket-list'));
							if($('.li-last').hasClass('li-active')){
								allin = 1;
							}
							_lis.each(function(){
								var _this = $(this)
								v_data.push(_this.attr('video-code'));
								p_data.push(_this.attr('prize'));
								n_data.push(_this.attr('set-name'));
							})
							if(!_userId){
								v_data = [];
								p_data = [];
								n_data = [];
								bridge.callHandler('loginOCHandler', function(response) {

								})
							}else{
								var _url = "pay.html?videoId="+v_data+"&userId="+_userId+"&prize="+p_data+"&videoName="+n_data+"&ifall="+allin;
								_url = encodeURI(_url);
								window.location.href = _url;
							}
						}
					})
				}else{
					tipShow('请更新版本后再进行支付');
				}
			}else if(_mobile=="android"&&!_ifshare){
				//安卓支付
			}else if(_mobile=="wx"||_mobile=="other"||_ifshare){
				_btn.click(function(e){
					tipShow('请下载app进行支付');
					setTimeout(function(){
						window.location.href=http_download;
					},1800)
					// e.preventDefault()
					// var _lis = $('.li-active:not(.li-last)',$('.ticket-list'));
					// if($('.li-last').hasClass('li-active')){
					// 	allin = 1;
					// }
					// _lis.each(function(){
					// 	var _this = $(this)
					// 	v_data.push(_this.attr('video-code'));
					// 	p_data.push(_this.attr('prize'));
					// 	n_data.push(encodeURIComponent(_this.attr('set-name')));
					// })
					// window.location.href="pay.html?videoId="+v_data+"&userId="+_userId+"&prize="+p_data+"&videoName="+n_data+"&ifall="+allin
				})
			}
		}
	}

	// 播放
	function playClick(){
		var _wrap = $('.ticket-list');
		var _lis = $('.li-play',_wrap);
		var _urlhead = http_api+"/info/video/videoDetail?videoId="
		_lis.each(function(e){
			var _this = $(this);
			_this.find('.btn-play').click(function(){
				var _code = _this.attr('video-code');
				_url = _urlhead+_code;
				$.ajax({
					type: "get",
					dataType: "jsonp",
					url: _url,
					async: false,
					success:function(data){
						var _begintime = new Date(data.data.showTime.time);
						var _nowtime = new Date();
						var _endtime = new Date(data.data.endTime.time);
						var vedioType = data.data.vedioType;
						if(_nowtime>_endtime){
							tipShow('该直播已结束');
							return;
						}else{
							if(_begintime<_nowtime){
								if(_mobile == "android"&&!_ifshare){
									window.playVideo.clickOnAndroid(_code,vedioType);
								}
							}else{
								tipShow("该直播尚未开始");
								return;
							}
						}
					},
					error:function(){
						tipShow("error")
					}
				})
			})
		})
	}

	// 伪优惠券
	function getCoupon(){
		$('.coupon-line').html(getRandomString(16));
	}

	// 生成随机数
	function getRandomString(len){
	    len = len || 32;  
	    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1  
	    var maxPos = $chars.length;  
	    var pwd = '';
	    for (i = 0; i < len; i++){
	        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));  
	    }
	    return pwd;
	}

	function getValue(key) {
		var name = key;
		var str = window.location.search;
		if(str.indexOf(name) != -1){
			var pos_start = str.indexOf(name) + name.length + 1;
			var pos_end = str.indexOf("&", pos_start);
			if(pos_end == -1){
				return decodeURIComponent(str.substring(pos_start));
			}else{
				return decodeURIComponent(str.substring(pos_start, pos_end));
			}
		}
	}

	function tipShow(content){
		if(!$('.tip-disk').length){
			$(document.body).append('<div class="tip-disk"><span></span></div>');
		}
		var _wrap = $('.tip-disk');
		_wrap.children('span').text(content);
		_wrap.stop(true,true).fadeIn('fast');
		_wrap.fadeOut(2000);
	}

	function loadTopbar(content){
		var _hUrl = "'http://"+window.location.host+"/'";
		var _html = '<header><h1>'+content+'</h1><div class="h-left"><a href="javascript:if(document.referrer.indexOf('+_hUrl+') == -1){window.location.href='+_hUrl+';}else{window.history.go(-1);}"><i class="icon iconfont">&#xe600;</i></a></div></header>';
		$(document.body).prepend(_html);
		$('#body').css('paddingTop',$('header').outerHeight())
	}
}